package com.future.common.security.config;

import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.future.common.security.annoation.Ignore;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @ClassName : PermitAllUrlProperties
 * @Author : lby
 * @Date: 2021/5/6 21:17
 * @Description : oauth2 读取配置文件
 */
@Slf4j
@Configuration
@ConditionalOnExpression("!'${security.oauth2.client.ignore-urls}'.isEmpty()")
@ConfigurationProperties(prefix = "security.oauth2.client")
public class PermitAllUrlProperties implements InitializingBean {
    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
    @Autowired
    private WebApplicationContext applicationContext;

    @Getter
    @Setter
    private List<String> ignoreUrls = new ArrayList<>();

    @Override
    public void afterPropertiesSet() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();


//        map.keySet().forEach(info -> {
//            HandlerMethod handlerMethod = map.get(info);
//
//            // 获取方法上边的注解 替代path variable 为 *
//            Ignore method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Ignore.class);
//            Optional.ofNullable(method)
//                    .ifPresent(inner -> info.getPatternsCondition().getPatterns()
//                            .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, StringPool.ASTERISK))));
//
//            // 获取类上边的注解, 替代path variable 为 *
//            Ignore controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Ignore.class);
//            Optional.ofNullable(controller)
//                    .ifPresent(inner -> info.getPatternsCondition().getPatterns()
//                            .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, StringPool.ASTERISK))));
//        });
        for (RequestMappingInfo info : map.keySet()) {
            HandlerMethod handlerMethod = map.get(info);
            Ignore method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Ignore.class);
            if (method != null) {
                Set<PathPattern> patterns = info.getPathPatternsCondition().getPatterns();
                if (patterns != null) {
                    for (PathPattern x : patterns) {
                        String url = x.getPatternString();
                        ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, StringPool.ASTERISK));
                    }
                }

            }
            Ignore controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Ignore.class);
            if (controller != null) {
                Set<PathPattern> patterns = info.getPathPatternsCondition().getPatterns();
                if (patterns != null) {
                    for (PathPattern x : patterns) {
                        String url = x.getPatternString();
                        ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, StringPool.ASTERISK));
                    }
                }
            }
        }

    }
}
